package com.gmss.crawler.module.paper.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmss.crawler.constants.Base;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.enums.AcademicianEnum;
import com.gmss.crawler.enums.CommonEnum;
import com.gmss.crawler.module.paper.domain.Paper;
import com.gmss.crawler.module.paper.service.IPaperService;
import com.gmss.crawler.module.patent.domain.Patent;
import com.gmss.crawler.module.person.controller.PersonInfoController;
import com.gmss.crawler.module.person.domain.PersonInfo;
import com.gmss.crawler.module.person.service.IPersonInfoService;
import com.gmss.crawler.module.title.domain.PersonTitle;
import com.gmss.crawler.module.title.service.IPersonTitleService;
import com.gmss.crawler.service.JQCrawlerService;
import com.gmss.crawler.service.ParseExcelService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 论文表 前端控制器
 * </p>
 *
 * @author Auto-generator
 * @since 2021-10-21
 */
@RestController
@RequestMapping("/paper")
public class PaperController extends Base {


    @Autowired
    private IPaperService iPaperService;
    @Resource
    private IPersonInfoService iPersonInfoService;
    @Autowired
    private IPersonTitleService iPersonTitleService;
    @Autowired
    private JQCrawlerService jqCrawlerService;

    @Resource
    private ParseExcelService parseExcelService;

    /**
     * 通过id查询
     */
    @GetMapping("/getById/{id}")
    public String getById(@PathVariable(value = "id") Integer id) {
        return respJson(CommonEnum.SUCCESS, iPaperService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    public String save(@RequestBody Paper paper) {
        iPaperService.save(paper);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 通过id删除
     */
    @DeleteMapping("/deleteById/{id}")
    public String delete(@PathVariable(value = "id") String ids) {
        String[] idsStrs = ids.split(",");
        for (String id : idsStrs) {
            iPaperService.removeById(Integer.parseInt(id));
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public String updateById(@RequestBody Paper paper) {
        iPaperService.updateById(paper);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 查询列表
     */
    @PostMapping("/list")
    public String list(@RequestBody PaperReqVo paper) {
        final LambdaQueryWrapper<Paper> lambda = new QueryWrapper<Paper>().lambda();
        this.buildCondition(lambda, paper);
        return respJson(CommonEnum.SUCCESS, iPaperService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    public String page(@RequestBody PaperReqVo pageParam) {
        final LambdaQueryWrapper<Paper> lambda = new QueryWrapper<Paper>().lambda();
        this.buildCondition(lambda, pageParam);
        final IPage<Paper> page = iPaperService.page(new Page<>(Constants.PAGE_NO, Constants.PAGE_SIZE), lambda);
        return respJson(CommonEnum.SUCCESS, page);
    }

    /**
     * 从数据库查出论文导入excel
     *
     * @param str
     * @return
     * @throws Exception
     */
    @PostMapping("/exportPaper")
    public String exportPaper(@RequestBody String str) throws Exception {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        Map<String, Object> map = JSON.parseObject(str);
        if (MapUtils.isEmpty(map))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!map.containsKey("filePath") || StringUtils.isBlank(map.get("filePath").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的路径不能为空！");
        }

        if (!map.containsKey("fileName") || StringUtils.isBlank(map.get("fileName").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称不能为空！");
        } else {
            String fileName = map.get("fileName").toString();
            String fileNamesuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if (!StringUtils.equalsAny(fileNamesuffix, "xlsx", "xls")) {
                return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称后缀不正确，后缀应该为xlsx或xls ");
            }
        }

        if (!map.containsKey("exportType") || StringUtils.isBlank(map.get("exportType").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出类型(exportType)不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划");
        }

        String exportType = map.get("exportType").toString();
        List<Paper> paperList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        switch (exportType) {
            case "0":
                list = iPersonInfoService.getAcademician();
                map.put("personTitles", list);
                paperList = iPaperService.queryPaperData(map);
                break;
            case "1":
                list = new ArrayList<>();
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_SPECIAL.getCode());
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_LECTURE.getCode());
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_YOUTH.getCode());
                map.put("personTitles", list);
                paperList = iPaperService.queryPaperData(map);
                break;
            case "2":
                break;
            case "3":
                break;
            case "4":
                break;
            default:
                paperList = iPaperService.queryPaperData(map);
                break;
        }

        boolean bool = iPaperService.writeExcel(map.get("filePath").toString(), map.get("fileName").toString(), paperList);
        if (bool) {
            return respJson(CommonEnum.SUCCESS, "导出excel路径:" + map.get("filePath").toString() + File.separator + map.get("fileName").toString());
        } else {
            return respJson(CommonEnum.FAILURE);
        }
    }


    @PostMapping("/saveAminerPaper")
    public String saveAminerPaper(@RequestBody String str) throws Exception {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        Map<String, Object> map = JSON.parseObject(str);
        if (MapUtils.isEmpty(map))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!map.containsKey("url") || StringUtils.isBlank(map.get("url").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "url不能为空！");
        }

        if (!map.containsKey("personId") || StringUtils.isBlank(map.get("personId").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "personId不能为空！");
        }
        Map<String, PersonInfo> aminerPersonMap = new HashMap<>();
        PersonInfo personInfo = new PersonInfo();
        personInfo.setId(Long.parseLong(map.get("personId").toString()));
        aminerPersonMap.put( "53f64553dabfaeaf590f3cce", personInfo);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageOffset", 0);
        paramsMap.put("pageSize", 20);
        paramsMap.put("aminerPersonId", "53f64553dabfaeaf590f3cce");
        jqCrawlerService.getPaperDataByAminerId(paramsMap,aminerPersonMap);
        aminerPersonMap.forEach((key,value) -> {
            List<Paper> paperList = value.getPaperList();
            if (CollectionUtils.isNotEmpty(paperList)) {
                iPaperService.saveBatch(paperList);
            }
        });

//        List<Map<String, Object>> list = AutoAminerCrawlerService.adminerSearch(map.get("url").toString());
//        if (CollectionUtils.isNotEmpty(list)) {
//            for (Map<String, Object> paperMap : list) {
//                Paper paper = new Paper().builder()
//                        .personId(Long.parseLong(map.get("personId").toString()))
//                        .keyword(paperMap.containsKey("keyword") ? paperMap.get("keyword").toString() : null)
//                        .otherAuthor(paperMap.containsKey("authors") ? paperMap.get("authors").toString() : null)
//                        .firstAuthor(paperMap.containsKey("firstAuthor") ? paperMap.get("firstAuthor").toString() : null)
//                        .describeData(paperMap.containsKey("descData") ? paperMap.get("descData").toString() : null)
//                        .publisher(paperMap.containsKey("publisher") ? paperMap.get("publisher").toString() : null)
//                        .publicationDate(paperMap.containsKey("publishDate") ? paperMap.get("publishDate").toString() : null)
//                        .title(paperMap.containsKey("title") ? paperMap.get("title").toString() : null)
//                        .languageStandard(paperMap.containsKey("languageStandard") ? Integer.parseInt(paperMap.get("languageStandard").toString()) : null)
//                        .build();
//                if (paperMap.containsKey("title")) {
//                    LambdaQueryWrapper<Paper> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    lambdaQueryWrapper.eq(Paper::getPersonId, map.get("personId"));
//                    lambdaQueryWrapper.eq(Paper::getTitle, paperMap.get("title").toString());
//                    List<Paper> papers = iPaperService.list(lambdaQueryWrapper);
//                    if (CollectionUtils.isNotEmpty(papers)) {
//                        paper.setId(papers.get(0).getId());
//                        iPaperService.saveOrUpdate(paper);
//                    } else {
//                        iPaperService.save(paper);
//                    }
//                }
//            }
//        }
        return respJson(CommonEnum.SUCCESS);
    }


    @PostMapping("/importPaperExcel")
    public String importPaperExcel() throws Exception {
        String path = "C:\\Users\\user\\Documents\\论文(1).xlsx";
        List<Paper> list = parseExcelService.parsePaperExcel(path, 11098L);
        for (Paper paper : list) {
            LambdaQueryWrapper<Paper> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(Paper::getPersonId, paper.getPersonId());
            lambdaQueryWrapper.eq(Paper::getTitle, paper.getTitle());
            List<Paper> queryList = iPaperService.list(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(queryList)) {
                paper.setId(queryList.get(0).getId());
                iPaperService.saveOrUpdate(paper);
            } else {
                iPaperService.save(paper);
            }
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<Paper> lambda, PaperReqVo param) {
        if (param.getId() != null) {
            lambda.eq(Paper::getId, param.getId());
        }
        if (param.getPersonId() != null) {
            lambda.eq(Paper::getPersonId, param.getPersonId());
        }
        if (param.getPaperType() != null) {
            lambda.eq(Paper::getPaperType, param.getPaperType());
        }
        if (param.getLanguageStandard() != null) {
            lambda.eq(Paper::getLanguageStandard, param.getLanguageStandard());
        }
        if (!StringUtils.isEmpty(param.getSubject())) {
            lambda.eq(Paper::getSubject, param.getSubject());
        }
        if (!StringUtils.isEmpty(param.getPublisher())) {
            lambda.eq(Paper::getPublisher, param.getPublisher());
        }
        if (!StringUtils.isEmpty(param.getKeyword())) {
            lambda.eq(Paper::getKeyword, param.getKeyword());
        }
        if (!StringUtils.isEmpty(param.getFirstAuthor())) {
            lambda.eq(Paper::getFirstAuthor, param.getFirstAuthor());
        }
        if (!StringUtils.isEmpty(param.getFirstReportAuthor())) {
            lambda.eq(Paper::getFirstReportAuthor, param.getFirstReportAuthor());
        }
        if (!StringUtils.isEmpty(param.getOtherAuthor())) {
            lambda.eq(Paper::getOtherAuthor, param.getOtherAuthor());
        }
        if (!StringUtils.isEmpty(param.getPeriodical())) {
            lambda.eq(Paper::getPeriodical, param.getPeriodical());
        }
        if (!StringUtils.isEmpty(param.getClassifyNum())) {
            lambda.eq(Paper::getClassifyNum, param.getClassifyNum());
        }
        if (!StringUtils.isEmpty(param.getColumnName())) {
            lambda.eq(Paper::getColumnName, param.getColumnName());
        }
        if (!StringUtils.isEmpty(param.getDoi())) {
            lambda.eq(Paper::getDoi, param.getDoi());
        }
        if (!StringUtils.isEmpty(param.getTitle())) {
            lambda.eq(Paper::getTitle, param.getTitle());
        }
        if (null != param.getIsIndex()) {
            lambda.eq(Paper::getIsIndex, param.getIsIndex());
        }
        if (!StringUtils.isEmpty(param.getIndexType())) {
            lambda.eq(Paper::getIndexType, param.getIndexType());
        }
        if (!StringUtils.isEmpty(param.getResearchPoint())) {
            lambda.eq(Paper::getResearchPoint, param.getResearchPoint());
        }
        if (!StringUtils.isEmpty(param.getDescribeData())) {
            lambda.eq(Paper::getDescribeData, param.getDescribeData());
        }
        if (!CollectionUtils.isEmpty(param.getCreateTimeList())) {
            lambda.ge(Paper::getCreateTime, param.getCreateTimeList().get(0));
            lambda.le(Paper::getCreateTime, param.getCreateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getCreateUser())) {
            lambda.eq(Paper::getCreateUser, param.getCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getUpdateTimeList())) {
            lambda.ge(Paper::getUpdateTime, param.getUpdateTimeList().get(0));
            lambda.le(Paper::getUpdateTime, param.getUpdateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getUpdateUser())) {
            lambda.eq(Paper::getUpdateUser, param.getUpdateUser());
        }
        lambda.orderBy(true, false, Paper::getId);
    }


    /**
     * 请求model
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class PaperReqVo extends Paper {
        private List<String> createTimeList; // 创建时间起止
        private List<String> updateTimeList; // 修改时间起止
    }


}
